package com.http.filterlianxi;

import java.io.*;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取表单提交的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 创建当前会话的session
        HttpSession session = req.getSession();
        // 验证当前用户名和密码是否正确
        if (VerifyAccount(username, password, session)) {
            // 用户名密码正确，则给session设置属性admin作为登录的标志
            session.setAttribute("admin", "admin");
            // 重定向到登陆后的页面
            resp.sendRedirect("/hello.html");
        } else {
            // 用户名或密码错误，则重定向到登录页面
            // 并给出提示
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>" +
                    "alert('您输入的账号或密码错误，请重新输入！');" +
                    "window.location.href='/pub/login.html';</script>");
        }
    }


    /**
     * 验证当前用户名和密码的正确性
     * 返回相应的boolean值
     *
     * @param username
     * @param password
     * @param session
     * @return
     */
    private boolean VerifyAccount(String username, String password, HttpSession session) {
        return (username.equals("admin") && password.equals("admin")) ||
                // 判断用户是否使用过注册功能
                (session.getAttribute("username") != null && session.getAttribute("username").equals(username)
                        && session.getAttribute("password").equals(password));
    }


    public void destroy() {
    }
}